import { AppDispatch } from '@/store';
export default async function data2stram(response: any, dispatch: AppDispatch, actionType: string, id: string) {
  if (!response.body) return;
  let returnText = '';
  const reader = response.body.getReader();
  const stream = new ReadableStream({
    async start(controller) {
      function fetchData() {
        reader.read().then(({ done, value }: any) => {
          if (done) {
            controller.close();
            return;
          }
          const chunkText = new TextDecoder().decode(value);
          chunkText.split('\n').forEach((line) => {
            if (line) {
              if (line === 'data: [DONE]') {
                return;
              }
              line = line.replaceAll('data: ', '');
              const data = JSON.parse(line);
              if (data.choices[0].finish_reason && data.choices[0].finish_reason === 'stop') {
                return;
              }
              if (data.choices[0].delta.content) {
                const text = data.choices[0].delta.content;
                returnText = returnText + text;
                // const dispatch: AppDispatch;
                dispatch({ type: actionType, payload: { id: id, input: returnText } });
                //   setData(returnText);
                // console.log(returnText);
              }
            }
          });
          fetchData();
        });
      }
      fetchData();
    },
  });
  await new Response(stream).text();
}
